package com.hugoo.imp.buzz;

import com.hugoo.core.db.Conn;
import com.hugoo.core.util.FileEncode;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;

/**
 *
 * @author Lovelock.Chan
 */
public class TxtFileValidation extends FileValidation {

    public TxtFileValidation(String sid, String scod) {
        super(sid, scod);
    }


    @Override
    public void validation(String file, Map mp) {
        BufferedReader br = null;
        try {
            FileEncode fe = new FileEncode(file);
            br = fe.getBufferedReader();
            String line, line2;
            String[] cl;
            int t = 0, v = 0, u = 0, i, m = col.size(), r = 0, p = 1;
            while (br.ready()) {
                r++;//记录行
                line = br.readLine();
                if (r < 3) {
                    if (line.endsWith("|")) {//1|2|3|4||x
                        p = 2;
                    }
                }
                line2 = line + "|x";
                if (super.col_title.startsWith(line)) {
                    t++;//标题
                    continue;
                }
                cl = line2.split("\\|");
                if (cl.length - p != m) {
                    v++;//无效行
                    info.add("第【" + r + "】行值【" + line + "】无效。");
                } else {
                    for (i = 0; i < m; i++) {
                        if (!super.validation(r, i, col.get(i), cl[i], info)) {
                            u++;//未通过验证
                        }
                    }
                }
            }
            if (v > 10) {
                mp.put(VALI_RUST, "M");//太多无效行数据
            } else if (r == (v + t)) {
                mp.put(VALI_RUST, "N");//无有效行数据
            } else if (u > 0) {
                mp.put(VALI_RUST, "V");//存在未通过验证行数据
            } else {
                mp.put(VALI_RUST, "Y");//验证通过
            }
            mp.put(VALI_REASON, "本次上传数据：共【" + r + "】行。其中标题【" + t + "】行，有效数据行【" + (r - t - v)
                    + "】，无效行【" + v + "】，未通过验证记录条数【" + u + "】。");
            if (!info.isEmpty()) {
                mp.put(VALI_INFO, getInfo());
            }
        } catch (FileNotFoundException ex) {
            mp.put(VALI_RUST, "F");
            mp.put(VALI_REASON, "上传文件未找到！");
        } catch (IOException ex) {
            mp.put(VALI_RUST, "F");
            mp.put(VALI_REASON, "上传文件读取错误！");
        } catch (Exception ex) {
            mp.put(VALI_RUST, "E");//系统处理数据异常
            mp.put(VALI_REASON, ex.getLocalizedMessage());
        } finally {
            Conn.release(br);
        }
    }
}
